#include <stdint.h>
#include <stdio.h>
#include "mfifoblock.h"

#define BUFFER_BLOCK_NUM  4
#define BUFFER_BLOCK_SIZE 32

static uint8_t BUFFER[BUFFER_BLOCK_NUM * BUFFER_BLOCK_SIZE] = {0};
static mblock_t BUFFER_MBLOCK[BUFFER_BLOCK_NUM] = {0};

void log_array(uint8_t *data, uint16_t len)
{
    for (uint16_t i = 0; i < len; i++)
    {
        printf("%02X ", *(data + i));
    }
}

int main(int argc, char const *argv[])
{
    static struct mfifoblock MFB = {0};

    mfifoblock_map(BUFFER_MBLOCK, BUFFER, BUFFER_BLOCK_NUM, BUFFER_BLOCK_SIZE);

    mfifoblock_init(&MFB, BUFFER_MBLOCK, BUFFER_BLOCK_NUM, BUFFER_BLOCK_SIZE);

    uint8_t *write_buf = NULL;

    uint32_t data_count = 0;

    for (uint32_t tc = 0; tc < 5; tc++)
    {
        printf("test count: %d\n", tc);

        while (mfifoblock_write_block_get(&MFB, &write_buf) == 0)
        {
            for (size_t i = 0; i < BUFFER_BLOCK_SIZE; i++)
            {
                *(write_buf + i) = data_count++ & 0xFF;
            }
            // log_array(write_buf, BUFFER_BLOCK_SIZE);
            // printf("\n");
            mfifoblock_write_block_increase(&MFB, BUFFER_BLOCK_SIZE);
            printf("wb wcount: %d, rcount: %d, space_len: %d\n", MFB.write_count, MFB.read_count,
                   mfifoblock_space_len(&MFB));

            if (mfifoblock_space_len(&MFB) > BUFFER_BLOCK_NUM)
            {
                printf("ERROR!!!\n");
                return 0;
            }
        }

        printf("read block\n");

        uint8_t *read_buf = NULL;
        uint16_t read_buf_len = 0;

        while (mfifoblock_read_block_get(&MFB, &read_buf, &read_buf_len) == 0)
        {
            mfifoblock_read_block_increase(&MFB);
            // log_array(read_buf, read_buf_len);
            // printf("\n");
            printf("rb wcount: %d, rcount: %d, space_len: %d\n", MFB.write_count, MFB.read_count,
                   mfifoblock_space_len(&MFB));

            if (mfifoblock_space_len(&MFB) > BUFFER_BLOCK_NUM)
            {
                printf("ERROR!!!\n");
                return 0;
            }
        }
    }

    return 0;
}
